package com.lzx.iteam.net;

import android.os.Message;
import com.lzx.iteam.bean.CRMLibraryListData;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONException;
import org.json.JSONObject;

public class CRMCreateMsg extends CcMsgStructure {

    private Message mCallBack;
    private String name;
    private String phone;

    public CRMCreateMsg(Message callback, String name, String phone) {
        this.mCallBack = callback;
        this.name = name;
        this.phone = phone;
    }

    public CRMCreateMsg(Message callback) {
        this.mCallBack = callback;
    }


    @Override
    public void onReceive(JSONObject data) {
        CRMLibraryListData listData = new CRMLibraryListData();
        if (!StringUtil.isEmpty(name)) {
            listData.setName(name);
        }
        if (!StringUtil.isEmpty(phone)) {
            listData.setPhone(phone);
        }
        try {
            JSONObject item = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
            if (item.has("_id")) {
                listData.set_id(item.getString("_id"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mCallBack != null) {
            mCallBack.arg1 = 0;
            mCallBack.obj = listData;
            mCallBack.sendToTarget();
        }
    }

    @Override
    public void onError(int error, Object ret) {
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mCallBack != null) {
            mCallBack.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mCallBack.obj = errorMsg;
            } else {
                mCallBack.obj = Constants.NETWORK_WRROR;
            }
            mCallBack.sendToTarget();
        }
    }
}
